package com.tju.resource.oauth.controller;

import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbOrderMapper;
import com.tju.resource.model.TbOrder;
import com.tju.resource.model.TbProdPlan;
import com.tju.resource.server.TbOrderService;
import com.tju.resource.server.TbProdPlanService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

@RestController
public class TbProdPlanController {

    public static final String prefix = "poplan";

    @Autowired
    TbProdPlanService service;
    @Autowired
    TbOrderMapper orderMapper;

    @Autowired
    TbOrderService oService;
    @Autowired
    TbOrderService tbOrderService;

    @PostMapping(prefix + "/getAll")
    @PreAuthorize("hasAuthority('sys:prod:list')")
    public Result<Object> getAll(@RequestBody ClientParameters params) {
        return service.getAll(params);
    }

    @PostMapping(prefix + "/add")
    @PreAuthorize("hasAuthority('sys:prod:add')")
    public Result<Object> add(@RequestBody TbProdPlan plan) {
        return baseVerify(plan, pl -> checkDupGN(pl) ? ResultUtil.error(ResultEnum.UNKONW_ERROR, "当前订单下已存在相同的品名!") : service.add(pl));
    }

    @PostMapping(prefix + "/upd")
    @PreAuthorize("hasAuthority('sys:prod:edit')")
    public Result<Object> upd(@RequestBody TbProdPlan plan) {
        return baseVerify(plan, pl -> {
            TbProdPlan tbProdPlan = service.get(pl.getId());
            if (EmptyUtils.isNotEmpty(tbProdPlan)) {
                TbOrder tbOrder = orderMapper.selectById(tbProdPlan.getOrderId());
                if (!StringUtils.equals(tbOrder.getOrderNumber(), pl.getOrderNumber())) {
                    throw new ServiceException("订单号不可修改!");
                } else {
                    if (StringUtils.equals(tbProdPlan.getGoodsName(), pl.getGoodsName())) {
                        return service.upd(pl);
                    } else {
                        return checkDupGN(pl) ? ResultUtil.error(ResultEnum.UNKONW_ERROR, "当前订单下已存在相同的品名!") : service.upd(pl);
                    }
                }
            } else {
                throw new ServiceException("生产计划不存在!");
            }

        });
    }

    @PostMapping(prefix + "/del")
    @PreAuthorize("hasAuthority('sys:prod:delete')")
    public Result<Object> del(@RequestBody TbProdPlan plan) {
        if (null != service.get(plan.getId())) {
            return service.del(plan);
        } else {
            throw new ServiceException("该生产计划不存在!");
        }
    }

    @SuppressWarnings("unchecked")
    public <T extends TbProdPlan, R extends Result<Object>> R baseVerify(T plan, Function<T, R> f) {
        Objects.requireNonNull(plan);
        Objects.requireNonNull(f);

        ClientParameters params = new ClientParameters();

        if (null != plan.getOrderNumber() && !StringUtils.equals(plan.getOrderNumber(), "")) {
            List<TbOrder> objectResult;

            params.setOne(plan.getOrderNumber());
            params.setLimit(10);
            params.setPage(1);

            objectResult = (List<TbOrder>) oService.selectTbOrderList(params).getData();

            if (0 == objectResult.size()) {
                throw new ServiceException("订单号不存在!");
            } else {
                if (null == plan.getGoodsName() || StringUtils.equals(plan.getGoodsName(), "")) {
                    throw new ServiceException("品名不可为空!");
                }

                return f.apply(plan);
            }
        } else {
            throw new ServiceException("订单号不可为空!");
        }
    }

    public boolean checkDupGN(TbProdPlan pl) {
        TbOrder tbOrder = tbOrderService.checkOrderNumberUnique(pl.getOrderNumber());
        List<TbProdPlan> plans = service.getByOR(tbOrder.getId());
        AtomicReference<Boolean> dupFlag = new AtomicReference<>(false);

        plans.forEach(ele -> {
            if (StringUtils.equals(ele.getGoodsName(), pl.getGoodsName())) {
                dupFlag.set(true);
            }
        });

        return dupFlag.get();
    }

}
